package com.example.spring_java_oj.Util;

import lombok.Data;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;

@Data
public class ImageUtil {
    private String str;//验证码文字
    private ByteArrayInputStream image;//验证码图片

    private int width = 240;//图片宽度
    private int height = 60;//图片高度

    private void init(){
        this.str = "";
        final BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        final Graphics g = image.getGraphics();
        g.setColor(getRandColor(200,250));
        g.fillRect(0,0,width,height);
        g.setFont(new Font("Times New Roman",Font.PLAIN,20));
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            final String rand = String.valueOf(random.nextInt(10));
            this.str += rand;
            g.setColor(getRandColor(20,110));
            g.drawString(rand,(width / 6) * i,46);
        }

        g.dispose();
        ByteArrayInputStream inputStream = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            final ImageOutputStream imageOut = ImageIO.createImageOutputStream(outputStream);
            ImageIO.write(image,"JPEG",imageOut);
            imageOut.close();
            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        }catch (Exception e){
            System.out.println("验证码图片生成失败~");
        }
        this.image = inputStream;
    }

    private Color getRandColor(int i, int i1) {
        Random random = new Random();
        if (i > 255){
            i = 255;
        }
        if (i1 > 255){
            i1 = 255;
        }
        int r = i + random.nextInt(i1 - i);
        int g = i + random.nextInt(i1 - i);
        int b = i + random.nextInt(i1 - i);
        return new Color(r,g,b);
    }

    public static ImageUtil getInstance(){
        return new ImageUtil();
    }

    private ImageUtil(){
        init();
    }
}
